<template>
  <div :class="['v-home', extendClass]">
    <div class="main-list">
      <div
        class="min-h-[60px] w-full flex items-center justify-between operation py-[10px] bg-white"
        v-if="isHeadEndShow"
      >
        <div class="w-[80%] flex items-center">
          <slot name="args"></slot>
          <span class="ml-3 conText text-lg font-bold">{{ titleText }}</span>
        </div>
        <div class="w-[20%] flex items-center justify-end">
          <!-- <slot name="args"></slot> -->
          <el-input
            v-if="hasSearch && hasKeyword"
            class="keyword"
            clearable
            placeholder="关键字"
            v-model="keyword"
          />
          <el-button
            class="mx-1.5"
            color="#626aef"
            @click="search"
            v-if="hasSearch"
            >查询
          </el-button>
          <el-button
            class="btn-add mr-1.5"
            color="#5bc0de"
            @click="edit()"
            v-if="hasAdd"
            >新增
          </el-button>
          <slot name="btns"></slot>
        </div>
      </div>
      <el-scrollbar ref="scrollbar">
        <el-table
          border
          cell-class-name="el-table-cell"
          header-cell-class-name="el-table-cell"
          ref="tableRef"
          stripe
          v-loading="loading"
          :data="pages"
          :highlight-current-row="type === 1"
          :row-class-name="tableRowClassName"
          :lazy="lazy"
          :row-key="lazy ? 'catCode' : ''"
          :load="load"
          :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
          @current-change="emitEvent('single', $event)"
          @selection-change="emitEvent('multiple', $event)"
          @expand-change="handleExpandChange"
          @sort-change="sortChange"
        >
          <slot name="left"></slot>
          <el-table-column
            class-name="snum"
            type="index"
            :fixed="true"
            :index="num"
            label="序号"
            width="60"
            v-if="hasIndex"
          />
          <slot></slot>
          <el-table-column
            class-name="oper"
            v-if="hasOper"
            label="操作"
            :width="width"
            fixed="right"
          >
            <template #default="scope">
              <el-button
                class="btn-option"
                @click="edit(scope.row)"
                v-if="hasEdit"
                type="primary"
                >编辑
              </el-button>
              <el-button
                class="btn-option"
                @click="edit(scope.row, true)"
                v-if="isView"
                type="primary"
                >浏览
              </el-button>
              <el-button
                class="btn-option"
                @click="remove(scope.row)"
                v-if="hasRemove"
                type="danger"
                >删除
              </el-button>
              <el-button
                class="btn-option"
                color="#f89e16"
                :disabled="true"
                v-if="showUserOperate"
                >停用
              </el-button>
              <el-button
                class="btn-option btn-long"
                color="#3c84d7"
                v-if="showUserOperate || showResetPwd"
                @click="resetPwd(scope.row)"
                >重置密码
              </el-button>

              <el-button
                class="btn-option"
                color="#f89e16"
                v-if="showMobileOperate && !scope.row.stopFlag"
                @click="openOrClose(scope.row)"
                >停用
              </el-button>
              <el-button
                class="btn-option"
                color="#3c84d7"
                v-if="showMobileOperate && scope.row.stopFlag"
                @click="openOrClose(scope.row)"
                >启用
              </el-button>
            </template>
          </el-table-column>
          <!-- <wdh-selection v-if="type == 2" /> -->
        </el-table>
      </el-scrollbar>

      <div
        class="pagination bg-white px-3 py-3 flex flex-row justify-between"
        v-if="isHeadEndShow && size != 1000"
        style="min-height: 57px"
      >
        <div v-if="isPaging">
          <div class="flex items-center">
            <span class="pr-3">列表显示</span>
            <el-select v-model="size" placeholder="请选择">
              <el-option
                v-for="i in [5, 8, 10, 20]"
                :key="i"
                :label="i + '条'"
                :value="i"
              ></el-option>
            </el-select>
          </div>
        </div>
        <div v-if="isPaging">
          <el-pagination
            background
            @size-change="sizeChange"
            @current-change="currentChange"
            :current-page="index"
            :page-sizes="[1, 3, 5, 8]"
            :page-size="size"
            layout="total,prev,pager,next,jumper"
            :total="total"
          ></el-pagination>
        </div>
      </div>
    </div>
    <slot name="edit"></slot>
  </div>
</template>

<script setup>
import { ref, computed, watch, nextTick, onMounted, defineEmits } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import * as $api from "@/api/api.js";

const props = defineProps({
  hasIndex: { type: Boolean, default: true },
  loading: { type: Boolean, default: false },
  datas: { type: Array, default: () => [] },
  total: { type: Number, default: 0 },
  extendClass: { type: String, default: "h-full" },
  hasSearch: { type: Boolean, default: true },
  hasKeyword: { type: Boolean, default: true },
  hasOper: { type: Boolean, default: true },
  hasRemove: { type: Boolean, default: true },
  hasEdit: { type: Boolean, default: true },
  rowClassName: { type: Function, default: () => "intro-x" },
  type: { type: Number, default: 0 },
  freshen: { type: Number, default: 0 },
  width: { type: String, default: "140" },
  pageListNo: { type: Number, default: 1 },
  isHeadEndShow: { type: Boolean, default: true },
  fixed: { type: Boolean, default: true },
  removeText: { type: String, default: "是否要删除此条数据？" },
  size: { type: Number, default: 10 },
  lazy: { type: Boolean, default: false },
  hasAdd: { type: Boolean, default: true },
  titleText: { type: String, default: "" },
  showUserOperate: { type: Boolean, default: false },
  showMobileOperate: { type: Boolean, default: false },
  showResetPwd: { type: Boolean, default: false },
  isView: { type: Boolean, default: false },
  isPaging: { type: Boolean, default: true },
});

const userKey = ref(localStorage.getItem("userKey"));
const keyword = ref("");
const index = ref(1);
const size = ref(props.size);
const oldDatas = ref(null);
const sortIndex = ref(1);
const tableRef = ref(null);
const emit = defineEmits([
  "search",
  "edit",
  "remove",
  "single",
  "multiple",
  "expand",
  "load",
  "resetPwd",
]);

// 计算分页数据或返回全部数据
const pages = computed(() => {
  if (props.isPaging) {
    // 如果isPaging为true，则进行分页
    return props.datas.slice(
      (index.value - 1) * size.value,
      index.value * size.value
    );
  } else {
    // 否则返回所有数据
    return props.datas;
  }
});
// 触发查询事件
const search = () => {
  emit("search", {
    keyword: keyword.value,
  });
};

// 编辑操作
const edit = (info, view) => {
  if (info) {
    info.isView = view;
  } else {
    info = { isAdd: true };
  }
  emit("edit", info);
};
const load = (tree, treeNode, resolve) => {
  emit("load", tree, treeNode, resolve);
};

// 重置密码
const resetPwd = (info) => {
  ElMessageBox.confirm("是否重置密码？", "提示", {
    type: "warning",
  }).then(() => {
    $api
      .UserResetPwd({
        plantKey: "",
        userKey: info.userKey,
      })
      .then((res) => {
        ElMessage({
          message: "重置成功！",
          type: "success",
        });
      })
      .catch((err) => {
        ElMessage.error(err);
      });
  });
};
// 启用/停用移动设备
const openOrClose = (info) => {
  if (info.stopFlag) {
    $api
      .CompanyAdminSetEnable({
        userKey: userKey.value,
        key: info.userKey,
      })
      .then((res) => {
        ElMessage({
          message: "启用成功！",
          type: "success",
        });
        search();
      })
      .catch((err) => {
        ElMessage.error(err);
      });
  } else {
    $api
      .CompanyAdminSetDisable({
        userKey: userKey.value,
        key: info.userKey,
      })
      .then((res) => {
        ElMessage({
          message: "停用成功！",
          type: "success",
        });
        search();
      })
      .catch((err) => {
        ElMessage.error(err);
      });
  }
};
// 删除操作
const remove = (info) => {
  ElMessageBox.confirm(props.removeText, "提示", {
    type: "warning",
  }).then(() => {
    emit("remove", info);
  });
};

// 每页条数改变
const sizeChange = (val) => {
  size.value = parseInt(val);
  nextTick(() => {
    scrollRef.value.update();
  });
};

// 当前页码改变
const currentChange = (val) => {
  index.value = parseInt(val);
};

// 排序
const sortChange = ({ prop, order }) => {
  if (order) {
    props.datas.sort(compare(prop, order));
  } else {
    for (let i = 0; i < props.datas.length; i++) {
      props.datas[i] = oldDatas.value[i];
    }
    sortIndex.value++;
  }
};
const num = (i) => {
  return (index.value - 1) * size.value + i + 1;
};
// 比较函数
const compare = (propertyName, sort) => {
  return (obj1, obj2) => {
    const value1 = obj1[propertyName];
    const value2 = obj2[propertyName];
    if (typeof value1 === "string" && typeof value2 === "string") {
      const res = value1.localeCompare(value2, "zh");
      return sort === "ascending" ? res : -res;
    } else {
      if (value1 <= value2) {
        return sort === "ascending" ? -1 : 1;
      } else if (value1 > value2) {
        return sort === "ascending" ? 1 : -1;
      }
    }
  };
};
const expandedRows = ref(new Set());

const tableRowClassName = ({ row, rowIndex }) => {
  let baseClass = (rowIndex + 1) % 2 === 0 ? "oddRow" : "evenRow";

  // 如果是懒加载模式
  if (props.lazy) {
    // 如果是展开的子节点，添加特殊的动画类
    if (row.catParentCode) {
      if (!expandedRows.value.has(row.catCode)) {
        expandedRows.value.add(row.catCode);
        return `${baseClass} intro-x animate-delay-${rowIndex}`;
      }
      return baseClass;
    }
  }

  // 非懒加载模式或顶级节点
  return `${baseClass} intro-x`;
};

// 监听展开事件
const handleExpandChange = (row, expanded) => {
  if (expanded) {
    // 清除之前展开节点的记录
    expandedRows.value.clear();
  }
  emit("expand", row, expanded);
};

// 通用的事件代理函数
const emitEvent = (eventName, eventArgs) => {
  emit(eventName, eventArgs);
};

const scrollRef = ref(null);

watch(
  () => props.datas,
  (newVal) => {
    console.log(props.datas);
    if (!oldDatas.value && newVal) {
      oldDatas.value = [...newVal];
    }
    if (props.type === 1 && newVal && newVal.length) {
      setTimeout(() => {
        tableRef.value.setCurrentRow(newVal[0]);
      }, 0);
    }
  },
  { deep: true, immediate: true }
);

watch(() => props.freshen, search);

onMounted(() => {
  search();
});
</script>

<style scoped lang="scss">
.el-select {
  width: 100px;
}

.btn-option {
  width: 50px;
  height: 25px;
  line-height: 25px;
  color: #ffffff;
  margin-right: 5px;

  &:hover {
    color: #ffffff;
  }
}

.btn-long {
  width: 80px;
}

/* 添加动画延迟类 */
@for $i from 1 through 10 {
  .animate-delay-#{$i} {
    animation-delay: #{$i * 0.1}s;
  }
}
</style>
